<?php
declare (strict_types = 1);

namespace app\wechat\controller;

use app\Request;
use app\BaseController;
use think\facade\Log;

class Index extends BaseController
{

    /**
     * 微信开发者填写的token值
     * 请自行配置
     * @var [type]
     */
    private $token = '';

    public function index(Request $request)
    {
        // 校验数据的合法性
        if ($request->param('echostr')) {
            return $this->checkAuth($request);
        }

        $postObj = file_get_contents("php://input");
        $postArr = simplexml_load_string($postObj, "SimpleXMLElement", LIBXML_NOCDATA);

        /**
         * 获取用户发送的信息
         * @var text/string
         */
        $postContent = $postArr->Content;
        $toUserName = $postArr->ToUserName;
        $fromUserName = $postArr->FromUserName;
        $time = time();
        $temXml = config('wechat.msg');

        if($postArr->MsgType=='event' && $postArr->Event=='subscribe'){
            //回复用户消息
            return $this->responseMsg($temXml, $fromUserName, $toUserName, $time, "欢迎来到秩简，我会的可多啦，扯皮是我的强项，无聊的话输入“笑话”可以给你讲个笑话，只要你不怕冷o(╯□╰)o，当前，我还可以帮你查询天气，比如“北京天气”");
        }

        $content = $this->robot($postContent);

        return $this->responseMsg($temXml, $fromUserName, $toUserName, $time, $content);

    }

    /**
     * 检测信息是否来自微信服务器
     * @param Request $request 请求对象
     */
    public function checkAuth($request)
    {
        $signature = $request->param('signature');
        $echostr = $request->param('echostr');
        $timestamp = $request->param('timestamp');
        $nonce = $request->param('nonce');

        // 校验信息是否从公众号服务器发送过来的
        $array = [$timestamp, $nonce, $this->token];
        sort($array);
        $string = implode($array);
        $string = sha1($string);
        if ($string === $signature && $echostr) {
            return $echostr;
        }
    }

    /**
     * [返回信息]
     * @param  [type] $fromUserName [description]
     * @param  [type] $toUserName   [description]
     * @param  [type] $time         [description]
     * @param  [type] $content      [description]
     * @return [type]               [description]
     */
    public function responseMsg($temXml, $fromUserName, $toUserName, $time, $content)
    {
        $info = sprintf($temXml, $fromUserName, $toUserName, $time, $content);
        return $info;
    }


    public function responseNews($temXml, $fromUserName, $toUserName, $time, $title, $description, $picUrl, $url)
    {
        $info = sprintf($temXml, $fromUserName, $toUserName, $time, $title, $description, $picUrl, $url);
        return $info;
    }


    /**
     * [responseWeather description]
     * @param  [type] $value [description]
     * @return [type]        [description]
     */
    public function responseWeather($value)
    {
        $content = "请输入你想要查询的城市，如：北京";
        $cities = file_get_contents('static/wechat/json/cities.json');
        $cities = json_decode($cities,true);

        foreach ($cities as $v) {
            if ($v['city'] == $value) {
                $cityid = $v['cityid'];
                return $this->getWeather($cityid);
            }
        };

        return $content;

    }

    /**
     * [getWeather description]
     * @param  [type] $cityid [description]
     * @return [type]         [description]
     */
    public function getWeather($cityid)
    {
        $getWeatherUrl = 'http://t.weather.sojson.com/api/weather/city/'.$cityid;

        $data = $this->httpGet($getWeatherUrl);

        $indexOf = strpos($data, '{');
        $dataJson = substr($data, $indexOf);
        $info = json_decode($dataJson, true);
        $city = $info['cityInfo']['city'];
        $weatherInfo = $info['data']['forecast'][0];
        $content = $city.'今天天气：'.$weatherInfo['type'].'，'.$weatherInfo['high'].'，'.$weatherInfo['low'].'，风向：'.$weatherInfo['fx'].'，风力：'.$weatherInfo['fl'].'，'.$weatherInfo['notice'];

        return $content;
    }

    /**
     * 动态获取access_token
     * @return [type] [description]
     */
    public function getAccessToken()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
        $appid = config('wechat.appID');
        $secret = config('wechat.appsecret');
        $url = sprintf($url, $appid, $secret);
        $json = $this->httpGet($url);
        // 将JSON转化为对象
        $obj = json_decode($json);
        $accessToken = $obj->access_token;
        return $accessToken;
    }

    /**
     * 机器人接口，这是免费的，功能已经够用了，当然你也可以自行对接其他的robot api
     * 在此特别感谢作者,注册之后就能获得
     * api_key
     * api_secret
     * @param  [type] $value [description]
     * @return [type]        [description]
     */
    public function robot($value)
    {
        $url = 'http://i.itpk.cn/api.php?question='.$value.'&api_key={%s}&api_secret={%s}';

        $str = file_get_contents($url);
        if ($value == "笑话") {
            $indexOf = strpos($str, '{');
            $dataJson = substr($str, $indexOf);
            $str = json_decode($dataJson, true);
            $str = $str['title']."\r\n".$str['content'];
        }
        return $str;
    }


    /**
     * 自定义菜单
     * @return [type] [description]
     */
    public function createMenus()
    {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accessToken;

        // 自定义菜单
        $data = '{
            "button":[
             {
                  "type":"view",
                  "name":"关于我",
                  "url":"http://www.kstone.top/"
              },
              {
                   "name":"菜单",
                   "sub_button":[
                   {
                       "type":"view",
                       "name":"搜索",
                       "url":"http://www.soso.com/"
                    },
                    {
                       "type":"click",
                       "name":"赞一下我们",
                       "key":"V1001_GOOD"
                    }]
               }]
        }';

        $output = $this->httpPost($url, $data);

        if ($output === false) {
            curl_error($output);
        }
        return $output;
    }


    /**
     * curl get获取数据请求
     * @param  [type] $url [description]
     * @return [type]      [description]
     */
    public function httpGet($url)
    {
        // 初始化curl
        $curl = curl_init();

        // curl请求的地址
        curl_setopt($curl, CURLOPT_URL, $url);

        // 启用数据流输出
        curl_setopt($curl, CURLOPT_HEADER, $url);

        // 把接收数据变成字符串，而不是直接输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        // 规避ssl证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        // 跳过host验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        // 调用第三方接口
        $data = curl_exec($curl);

        // 关闭入口
        curl_close($curl);

        return $data;
    }


    /**
     * curl post发送数据请求
     * @param  [type] $url  [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function httpPost($url, $data)
    {
        // 初始化，创建curl句柄
        $curl = curl_init();
        // 设置curl
        curl_setopt($curl, CURLOPT_URL, $url);
        // 捕获内容但不输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 模拟发送post请求
        curl_setopt($curl, CURLOPT_POST, 1);
        // 发送post请求时传递数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        // 规避ssl证书检查s
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // 跳过host验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        // 输出curl内容
        $output = curl_exec($curl);

        curl_close($curl);

        return $output;
    }

}
